package com.xdemo.codec;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.xdemo.msg.BaseMessage;
import com.xdemo.msg.IMessage;
import com.xdemo.msg.IMessageRecognizer;

public class MessageDecoder extends FrameDecoder{
	
	private IMessageRecognizer<Integer,Integer> recognizer;
	
	public MessageDecoder(IMessageRecognizer<Integer,Integer> recognizer) {
		this.recognizer = recognizer;
	}

	@Override
	protected Object decode(ChannelHandlerContext context,
			Channel channel, ChannelBuffer buffer)
			throws Exception {
		if(buffer.readableBytes() < 2) {
			return null;
		}
		buffer.markReaderIndex();
		int _len = buffer.readInt();
		if(buffer.readableBytes() < _len) {
			buffer.resetReaderIndex();
			return null;
		}
		int _type = buffer.readInt();
		IMessage<Integer> _msg = recognizer.createMessage(_type);
		if(_msg == null || !(_msg instanceof BaseMessage)) {
			return null;
		}
		BaseMessage _baseMsg = (BaseMessage)_msg;
		_baseMsg.setBuffer(buffer);
		_baseMsg.read();
		return _msg;
	}

}
